import { router, addRoutes } from '@/router'
import { getToken } from '@/composables/auth'
import { computed } from 'vue'
import { toast, showFullLoding, noshowFullLoding } from '@/composables/util'
import store from './store'
import { addMenus } from '@/router/addMenus'

// 全局前置守卫
let hasGetInfo = false
router.beforeEach(async (to, from, next) => {
  // 显示进度条
  showFullLoding()

  const token = getToken()
  // 没有登录，强制跳转回登录页
  // if (!token && to.path !== '/login' && to.path !== '/') {
  if (!token && to.path !== '/login') {
    toast('跳转失败', '你还没有登录，请先登录😊', 'error')
    return next({ path: '/login' })
  }

  // 防止重复登录
  if (token && to.path == '/login') {
    toast('跳转失败', '你已登录,请勿重复登录🤗', 'error')
    return next({ path: from.path ? from.path : '/' })
  }

  // 如果登录成功，自动获取用户信息并存储在vuex中
  // if (token) {
  //   await store.dispatch('GET_INFO')
  // }
  let hasNewRoutes = false
  if (token && !hasGetInfo) {
    let { menus } = await store.dispatch('GET_INFO')
    const asideMenus = computed(() => [...menus, ...addMenus])
    hasGetInfo = true
    // 动态添加路由
    hasNewRoutes = addRoutes(asideMenus.value)
  }

  // 设置路由标题
  // console.log(to.meta.title)
  if (to.meta.title == '404页面😭') {
    document.title = '404页面😭'
  } else {
    document.title =
      (to.meta.title ? to.meta.title : '') + ' - 商城后台管理系统'
  }
  // let title = (to.meta.title ? to.meta.title : '') + ' - 商城后台管理系统'
  // document.title = title

  // next()
  hasNewRoutes ? next(to.fullPath) : next()
})

router.afterEach(() => {
  // 隐藏全局进度条
  noshowFullLoding()
})
